// 全局变量
let customersTable, metersTable, readingsTable, priceHistoryTable;
let customerTypeChart, monthlyConsumptionChart;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化侧边栏
    initializeSidebar();

    // 加载默认页面（仪表板）
    loadPage('dashboard');
    
    // 初始化退出按钮
    document.getElementById('logoutBtn').addEventListener('click', logout);
});

// 加载页面内容
function loadPage(page) {
    fetch(`/admin/templates/${page}.html`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('content').innerHTML = html;
            
            // 根据页面类型初始化不同功能
            switch(page) {
                case 'dashboard':
                    initializeDashboard();
                    break;
                case 'customers':
                    initializeCustomersTable();
                    break;
                case 'meters':
                    initializeMetersTable();
                    break;

                case 'meter-reading':
                    initializeReadingsTable();
                    break;
                case 'pricing':
                    initializePricing();
                    break;
            }
        })
        .catch(error => {
            console.error('加载页面失败：', error);
            showAlert('加载页面失败，请稍后重试！', 'danger');
        });
}

// 初始化侧边栏
function initializeSidebar() {
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有导航项的active类
            document.querySelectorAll('.nav-link').forEach(item => {
                item.classList.remove('active');
            });
            
            // 为当前点击的导航项添加active类
            this.classList.add('active');
            
            // 获取要加载的页面名称
            const page = this.getAttribute('data-page');
            loadPage(page);
        });
    });
}

// 加载最近抄表记录
function loadRecentReadings() {
    $.ajax({
        url: '/api/meter-readings/recent',
        method: 'GET',
        success: function(data) {
            const tbody = $('#recentReadings');
            tbody.empty();
            
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(reading => {
                    const meterInfo = reading.meter ? reading.meter.meterCode : '未知';
                    const customerInfo = reading.meter && reading.meter.customer ? 
                        reading.meter.customer.customerName : '未知';
                    const currentReading = reading.currentReading ? 
                        parseFloat(reading.currentReading).toFixed(2) : '0.00';
                    const readingDate = reading.readingDate ? 
                        formatDate(reading.readingDate) : '未知';
                    
                    tbody.append(`
                        <tr>
                            <td>${meterInfo}</td>
                            <td>${customerInfo}</td>
                            <td class="text-right">${currentReading}</td>
                            <td>${readingDate}</td>
                        </tr>
                    `);
                });
            } else {
                tbody.append(`
                    <tr>
                        <td colspan="4" class="text-center text-muted">
                            <i class="fas fa-info-circle"></i> 暂无抄表记录
                        </td>
                    </tr>
                `);
            }
        },
        error: function(error) {
            console.error('加载最近抄表记录失败:', error);
            const tbody = $('#recentReadings');
            tbody.html(`
                <tr>
                    <td colspan="4" class="text-center text-danger">
                        <i class="fas fa-exclamation-circle"></i> 加载失败，请刷新重试
                    </td>
                </tr>
            `);
        }
    });
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '未知';
    try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '未知';
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    } catch (e) {
        console.error('日期格式化错误:', e);
        return '未知';
    }
}

// 初始化仪表板
function initializeDashboard() {
    // 加载统计数据
    loadDashboardStats();
    
    // 加载最近抄表记录
    loadRecentReadings();
    
    // 初始化图表
    initializeCharts();
    
    // 设置定时刷新
    setInterval(function() {
        loadDashboardStats();
        loadRecentReadings();
    }, 60000); // 每分钟刷新一次
}

// 加载仪表盘统计数据
function loadDashboardStats() {
    // 获取客户总数
    $.ajax({
        url: '/api/customers/count',
        method: 'GET',
        success: function(count) {
            $('#totalCustomers').text(count);
        },
        error: function(error) {
            console.error('获取客户总数失败:', error);
        }
    });

    // 获取电表总数
    $.ajax({
        url: '/api/meters/count',
        method: 'GET',
        success: function(count) {
            $('#totalMeters').text(count);
        },
        error: function(error) {
            console.error('获取电表总数失败:', error);
        }
    });

    // 获取待抄表数
    $.ajax({
        url: '/api/meter-readings/count/pending',
        method: 'GET',
        success: function(count) {
            $('#pendingReadings').text(count);
            // 如果有待抄表，添加闪烁效果
            if (count > 0) {
                $('#pendingReadings').parent().addClass('text-warning blink');
            } else {
                $('#pendingReadings').parent().removeClass('text-warning blink');
            }
        },
        error: function(error) {
            console.error('获取待抄表数失败:', error);
        }
    });

    // 获取本月抄表数
    $.ajax({
        url: '/api/meter-readings/count/monthly',
        method: 'GET',
        success: function(count) {
            $('#monthlyReadings').text(count);
        },
        error: function(error) {
            console.error('获取本月抄表数失败:', error);
        }
    });
}

// 添加CSS样式
const style = document.createElement('style');
style.textContent = `
    .blink {
        animation: blink-animation 1s steps(5, start) infinite;
    }
    @keyframes blink-animation {
        to {
            visibility: hidden;
        }
    }
`;
document.head.appendChild(style);

// 定时刷新仪表盘数据
setInterval(function() {
    loadDashboardStats();
    loadRecentReadings();
}, 60000); // 每分钟刷新一次

// 初始化客户管理表格
function initializeCustomersTable() {
    customersTable = $('#customersTable').DataTable({
        language: {
            url: '/admin/js/Chinese.json'
        },
        columns: [
            { data: 'customerNo' },
            { data: 'customerName' },
            { data: 'address' },
            { data: 'phone' },
            { data: 'electricityType' },
            {
                data: null,
                render: function(data, type, row) {
                    return `
                        <button class="btn btn-sm btn-info btn-action" onclick="editCustomer('${row.customerNo}')">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger btn-action" onclick="deleteCustomer('${row.customerNo}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    `;
                }
            }
        ]
    });
    
    // 加载客户数据
    loadCustomers();
}

// 加载客户数据
function loadCustomers() {
    $.ajax({
        url: '/api/customers',
        method: 'GET',
        success: function(data) {
            // 适配DataTables字段
            const customers = data.map(item => ({
                customerNo: item.customerCode,
                customerName: item.customerName,
                address: item.address,
                phone: item.phone,
                electricityType: item.customerType === 'RESIDENTIAL' ? '居民用电' : '商业用电'
            }));
            customersTable.clear().rows.add(customers).draw();
        },
        error: function() {
            showAlert('加载客户数据失败，请稍后重试！', 'danger');
        }
    });
}

// 加载客户数据到表单（编辑）
function loadCustomerData(customerNo) {
    $.ajax({
        url: '/api/customers',
        method: 'GET',
        success: function(data) {
            const customer = data.find(item => item.customerCode == customerNo);
            if (customer) {
                $('#customerNo').val(customer.customerCode).prop('disabled', true);
                $('#customerName').val(customer.customerName);
                $('#address').val(customer.address);
                $('#phone').val(customer.phone);
                $('#electricityType').val(customer.customerType);
                $('#customerModal').data('edit-id', customer.customerId);
            }
        }
    });
}

// 编辑客户按钮
function editCustomer(customerNo) {
    openCustomerModal(customerNo);
}

// 删除客户按钮
function deleteCustomer(customerNo) {
    if (!confirm('确定要删除该客户吗？')) return;
    // 先查出customerId
    $.ajax({
        url: '/api/customers',
        method: 'GET',
        success: function(data) {
            const customer = data.find(item => item.customerCode == customerNo);
            if (customer) {
                $.ajax({
                    url: '/api/customers/' + customer.customerId,
                    method: 'DELETE',
                    success: function() {
                        showAlert('删除成功', 'success');
                        loadCustomers();
                    },
                    error: function() {
                        showAlert('删除失败', 'danger');
                    }
                });
            }
        }
    });
}

// 保存客户（新增/编辑）
$(document).on('click', '#saveCustomer', function() {
    const customerId = $('#customerModal').data('edit-id');
    const customer = {
        customerCode: Number($('#customerNo').val()),
        customerName: $('#customerName').val(),
        address: $('#address').val(),
        phone: $('#phone').val(),
        customerType: $('#electricityType').val()
    };
    let method, url;
    if (customerId) {
        method = 'PUT';
        url = '/api/customers/' + customerId;
    } else {
        method = 'POST';
        url = '/api/customers';
    }
    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(customer),
        success: function() {
            showAlert('保存成功', 'success');
            $('#customerModal').modal('hide');
            loadCustomers();
            $('#customerModal').removeData('edit-id');
            $('#customerNo').prop('disabled', false);
        },
        error: function() {
            showAlert('保存失败', 'danger');
        }
    });
});

// 打开新增客户时，确保户号可编辑
$(document).on('click', '.btn-primary[onclick="openCustomerModal()"]', function() {
    $('#customerNo').prop('disabled', false);
    $('#customerModal').removeData('edit-id');
});

// 初始化电表管理表格
function initializeMetersTable() {
    metersTable = $('#metersTable').DataTable({
        language: {
            url: '/admin/js/Chinese.json'
        },
        columns: [
            { data: 'meterCode' },
            { data: 'customerCode' },
            { data: 'customerName' },
            { 
                data: 'installationDate',
                render: function(data) {
                    return data ? new Date(data).toLocaleString() : '';
                }
            },
            { 
                data: 'multiplier',
                render: function(data) {
                    return data ? data.toFixed(2) : '0.00';
                }
            },
            { 
                data: 'currentReading',
                render: function(data) {
                    return data ? data.toFixed(2) : '0.00';
                }
            },
            {
                data: null,
                render: function(data) {
                    return `
                        <button class="btn btn-sm btn-info" onclick="editMeter(${data.meterId})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteMeter(${data.meterId})">
                            <i class="fas fa-trash"></i>
                        </button>
                    `;
                }
            }
        ]
    });
    
    // 加载电表数据
    loadMeters();
    
    // 绑定保存按钮事件
    $('#saveMeter').off('click').on('click', saveMeter);
}

// 加载电表数据
function loadMeters() {
    $.ajax({
        url: '/api/meters',
        method: 'GET',
        success: function(data) {
            metersTable.clear().rows.add(data).draw();
        },
        error: function() {
            showAlert('加载电表数据失败', 'danger');
        }
    });
}

// 加载客户列表
function loadCustomerList() {
    $.ajax({
        url: '/api/customers',
        method: 'GET',
        success: function(data) {
            const select = $('#customerId');
            select.empty();
            select.append('<option value="">请选择客户</option>');
            data.forEach(function(customer) {
                select.append(`<option value="${customer.customerId}">${customer.customerCode} - ${customer.customerName}</option>`);
            });
        },
        error: function() {
            showAlert('加载客户列表失败', 'danger');
        }
    });
}

// 打开电表模态框
function openMeterModal(meterId = null) {
    const modal = $('#meterModal');
    const form = $('#meterForm')[0];
    form.reset();
    $('#meterId').val('');
    
    // 加载客户列表
    loadCustomerList();
    
    if (meterId) {
        // 编辑模式
        $.ajax({
            url: `/api/meters/${meterId}`,
            method: 'GET',
            success: function(data) {
                $('#meterId').val(data.meterId);
                $('#meterCode').val(data.meterCode);
                $('#customerId').val(data.customerId);
                $('#installationDate').val(data.installationDate ? new Date(data.installationDate).toISOString().slice(0, 16) : '');
                $('#multiplier').val(data.multiplier);
                $('#currentReading').val(data.currentReading);
                modal.modal('show');
            },
            error: function() {
                showAlert('加载电表数据失败', 'danger');
            }
        });
    } else {
        // 新增模式
        modal.modal('show');
    }
}

// 保存电表
function saveMeter() {
    const meterId = $('#meterId').val();
    const data = {
        meterCode: $('#meterCode').val(),
        customerId: $('#customerId').val(),
        installationDate: new Date($('#installationDate').val()).toISOString(),
        multiplier: parseFloat($('#multiplier').val()),
        currentReading: parseFloat($('#currentReading').val())
    };
    
    if (meterId) {
        // 更新
        $.ajax({
            url: `/api/meters/${meterId}`,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function() {
                showAlert('保存成功', 'success');
                $('#meterModal').modal('hide');
                loadMeters();
            },
            error: function(xhr) {
                let message = '保存失败';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message += ': ' + xhr.responseJSON.message;
                }
                showAlert(message, 'danger');
            }
        });
    } else {
        // 新增
        $.ajax({
            url: '/api/meters',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function() {
                showAlert('添加成功', 'success');
                $('#meterModal').modal('hide');
                loadMeters();
            },
            error: function(xhr) {
                let message = '添加失败';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message += ': ' + xhr.responseJSON.message;
                }
                showAlert(message, 'danger');
            }
        });
    }
}

// 编辑电表
function editMeter(meterId) {
    openMeterModal(meterId);
}

// 删除电表
function deleteMeter(meterId) {
    if (confirm('确定要删除这个电表吗？')) {
        $.ajax({
            url: `/api/meters/${meterId}`,
            method: 'DELETE',
            success: function() {
                showAlert('删除成功', 'success');
                loadMeters();
            },
            error: function() {
                showAlert('删除失败', 'danger');
            }
        });
    }
}



// 初始化抄表记录表格
function initializeReadingsTable() {
    readingsTable = $('#readingsTable').DataTable({
        language: {
            url: '/admin/js/Chinese.json'
        },
        ajax: {
            url: '/api/meter-readings',
            dataSrc: function(json) {
                // 确保返回的是数组
                return Array.isArray(json) ? json : [];
            },
            error: function(xhr, error, thrown) {
                console.error('DataTables Ajax error:', error);
                console.error('Server response:', xhr.responseText);
                showAlert('加载数据失败：' + error, 'danger');
            }
        },
        processing: true,
        serverSide: false,
        columns: [
            { 
                data: 'readingId',
                defaultContent: ''
            },
            { 
                data: null,
                render: function(data, type, row) {
                    return row.meter ? row.meter.meterCode : '';
                },
                title: '电表号'
            },
            { 
                data: null,
                render: function(data, type, row) {
                    if (row.meter && row.meter.customer) {
                        return row.meter.customer.customerName + 
                               '<br/>电话: ' + row.meter.customer.phone +
                               '<br/>地址: ' + row.meter.customer.address;
                    }
                    return '';
                },
                title: '客户信息'
            },
            { 
                data: 'previousReading',
                defaultContent: '0.00',
                render: function(data) {
                    return data ? parseFloat(data).toFixed(2) : '0.00';
                }
            },
            { 
                data: 'currentReading',
                defaultContent: '0.00',
                render: function(data) {
                    return data ? parseFloat(data).toFixed(2) : '0.00';
                }
            },
            { 
                data: 'electricityUsage',
                defaultContent: '0.00',
                render: function(data) {
                    return data ? parseFloat(data).toFixed(2) : '0.00';
                }
            },
            { 
                data: 'readingDate',
                render: function(data) {
                    return data ? new Date(data).toLocaleDateString() : '';
                },
                defaultContent: ''
            },
            {
                data: null,
                render: function(data, type, row) {
                    if (!row.readingId) return '';
                    return `
                        <button class="btn btn-sm btn-info btn-action" onclick="editReading(${row.readingId})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger btn-action" onclick="deleteReading(${row.readingId})">
                            <i class="fas fa-trash"></i>
                        </button>
                    `;
                }
            }
        ]
    });
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function formatDateTime(dateTimeString) {
    if (!dateTimeString) return '';
    const date = new Date(dateTimeString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

function loadReadings() {
    fetch('/api/meter-readings')
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('readingsTableBody');
            tbody.innerHTML = '';
            data.forEach(reading => {
                tbody.innerHTML += `
                    <tr>
                        <td>${reading.readingId}</td>
                        <td>${reading.meterId}</td>
                        <td>${reading.previousReading}</td>
                        <td>${reading.currentReading}</td>
                        <td>${reading.electricityUsage}</td>
                        <td>${reading.readingDate}</td>
                        <td>${reading.createdTime}</td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="editReading(${JSON.stringify(reading).replace(/"/g, '&quot;')})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteReading(${reading.readingId})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });
        })
        .catch(error => console.error('Error:', error));
}

function openAddModal() {
    document.getElementById('readingId').value = '';
    document.getElementById('readingForm').reset();
    document.getElementById('modalTitle').textContent = '新增抄表记录';
    const readingModal = new bootstrap.Modal(document.getElementById('readingModal'));
    readingModal.show();
}

function editReading(reading) {
    document.getElementById('readingId').value = reading.readingId;
    document.getElementById('meterIdInput').value = reading.meterId;
    document.getElementById('previousReading').value = reading.previousReading;
    document.getElementById('currentReading').value = reading.currentReading;
    document.getElementById('readingDate').value = reading.readingDate;
    document.getElementById('modalTitle').textContent = '编辑抄表记录';
    const readingModal = new bootstrap.Modal(document.getElementById('readingModal'));
    readingModal.show();
}

function saveReading() {
    const reading = {
        readingId: document.getElementById('readingId').value || null,
        meterId: document.getElementById('meterIdInput').value,
        previousReading: document.getElementById('previousReading').value,
        currentReading: document.getElementById('currentReading').value,
        readingDate: document.getElementById('readingDate').value
    };

    const url = reading.readingId ? `/api/meter-readings/${reading.readingId}` : '/api/meter-readings';
    const method = reading.readingId ? 'PUT' : 'POST';

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(reading)
    })
    .then(response => response.json())
    .then(() => {
        const readingModal = bootstrap.Modal.getInstance(document.getElementById('readingModal'));
        readingModal.hide();
        loadReadings();
    })
    .catch(error => console.error('Error:', error));
}

function deleteReading(id) {
    if (confirm('确定要删除这条记录吗？')) {
        fetch(`/api/meter-readings/${id}`, {
            method: 'DELETE'
        })
        .then(() => loadReadings())
        .catch(error => console.error('Error:', error));
    }
}

function searchReadings() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const meterId = document.getElementById('meterId').value;

    let url = '/api/meter-readings';
    if (startDate && endDate) {
        url = `/api/meter-readings/date-range?startDate=${startDate}&endDate=${endDate}`;
    } else if (meterId) {
        url = `/api/meter-readings/meter/${meterId}`;
    }

    fetch(url)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('readingsTableBody');
            tbody.innerHTML = '';
            data.forEach(reading => {
                tbody.innerHTML += `
                    <tr>
                        <td>${reading.readingId}</td>
                        <td>${reading.meterId}</td>
                        <td>${reading.previousReading}</td>
                        <td>${reading.currentReading}</td>
                        <td>${reading.electricityUsage}</td>
                        <td>${reading.readingDate}</td>
                        <td>${reading.createdTime}</td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="editReading(${JSON.stringify(reading).replace(/"/g, '&quot;')})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteReading(${reading.readingId})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });
        })
        .catch(error => console.error('Error:', error));
}

// 初始化电价设置页面
function initializePricing() {
    // 加载当前电价
    loadCurrentPrices();
    
    // 初始化价格历史表格
    priceHistoryTable = $('#priceHistoryTable').DataTable({
        language: {
            url: '/admin/js/Chinese.json'
        },
        order: [[0, 'desc']]
    });
    
    // 加载价格历史
    loadPriceHistory();
    
    // 绑定事件
    bindPricingEvents();
}

// 加载当前电价
function loadCurrentPrices() {
    $.ajax({
        url: '/api/electricity-price/current',
        method: 'GET',
        success: function(data) {
            if (data) {
                $('#residentialPriceDisplay').text(data.residentialPrice ? data.residentialPrice.toFixed(2) : '0.00');
                $('#commercialPriceDisplay').text(data.commercialPrice ? data.commercialPrice.toFixed(2) : '0.00');
            }
        },
        error: function() {
            showAlert('加载当前电价失败', 'danger');
        }
    });
}

// 加载价格历史
function loadPriceHistory() {
    $.ajax({
        url: '/api/electricity-price/history',
        method: 'GET',
        success: function(data) {
            priceHistoryTable.clear();
            
            // 按客户类型分组存储上一次的价格
            let priceMap = {
                'RESIDENTIAL': [],
                'COMMERCIAL': []
            };
            
            // 首先将数据按类型分组
            data.forEach(function(item) {
                priceMap[item.customerType].push(item);
            });
            
            // 处理每种类型的价格历史
            for (let type in priceMap) {
                let prices = priceMap[type];
                // 按日期降序排序
                prices.sort((a, b) => new Date(b.effectiveDate) - new Date(a.effectiveDate));
                
                // 处理每条记录
                for (let i = 0; i < prices.length; i++) {
                    let item = prices[i];
                    let previousPrice = i < prices.length - 1 ? prices[i + 1].unitPrice : null;
                    
                    priceHistoryTable.row.add([
                        item.effectiveDate,
                        item.customerType === 'RESIDENTIAL' ? '居民用电' : '商业用电',
                        previousPrice ? previousPrice.toFixed(2) : '-',
                        item.unitPrice.toFixed(2),
                        '-' // 操作人（如需可扩展）
                    ]);
                }
            }
            
            // 重新按日期降序排序整个表格
            priceHistoryTable.order([0, 'desc']).draw();
        },
        error: function() {
            showAlert('加载价格历史失败', 'danger');
        }
    });
}

// 绑定电价设置相关事件
function bindPricingEvents() {
    // 保存电价
    $('#savePrice').off('click').on('click', function() {
        const type = $('#priceType').val();
        const price = type === 'RESIDENTIAL' ? 
            $('#residentialPrice').val() : 
            $('#commercialPrice').val();
            
        if (!price || isNaN(price) || price <= 0) {
            showAlert('请输入有效的电价', 'danger');
            return;
        }

        $.ajax({
            url: '/api/electricity-price',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                customerType: type,
                unitPrice: parseFloat(price),
                effectiveDate: new Date().toISOString().split('T')[0]
            }),
            success: function(response) {
                showAlert('电价修改成功', 'success');
                $('#priceModal').modal('hide');
                
                // 清空输入框
                $('#residentialPrice').val('');
                $('#commercialPrice').val('');
                
                // 立即刷新显示
                setTimeout(function() {
                    loadCurrentPrices();
                    loadPriceHistory();
                }, 100);
            },
            error: function(xhr) {
                let errorMessage = '电价修改失败';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage += ': ' + xhr.responseJSON.message;
                }
                showAlert(errorMessage, 'danger');
            }
        });
    });
}

// 打开电价设置模态框
function openPriceModal(type) {
    $('#priceType').val(type);
    $('#residentialPrice').val('');
    $('#commercialPrice').val('');
    
    if (type === 'RESIDENTIAL') {
        $('#residentialPrice').closest('.form-group').show();
        $('#commercialPrice').closest('.form-group').hide();
    } else {
        $('#residentialPrice').closest('.form-group').hide();
        $('#commercialPrice').closest('.form-group').show();
    }
    
    $('#priceModal').modal('show');
}

// 打开客户模态框
function openCustomerModal(customerNo = null) {
    const modal = $('#customerModal');
    if (customerNo) {
        // 编辑模式 - 加载客户数据
        loadCustomerData(customerNo);
    } else {
        // 新增模式 - 清空表单
        modal.find('form')[0].reset();
    }
    modal.modal('show');
}

// 加载电表列表
function loadMeterList() {
    $.ajax({
        url: '/api/meters/all',
        method: 'GET',
        success: function(data) {
            const select = $('#meterNoSelect');
            select.empty();
            select.append('<option value="">请选择电表</option>');
            
            data.forEach(meter => {
                const customerInfo = meter.customer ? 
                    `${meter.customer.customerName} (${meter.customer.customerCode})` : '';
                select.append(`<option value="${meter.meterId}">
                    ${meter.meterCode} - ${customerInfo}
                </option>`);
            });
        },
        error: function(error) {
            console.error('加载电表列表失败:', error);
            showAlert('加载电表列表失败，请重试！', 'danger');
        }
    });
}

// 当选择电表时重置读数输入框
$('#meterNoSelect').change(function() {
    // 清空读数输入框
    $('#previousReading').val('');
    $('#currentReading').val('');
    $('#consumption').text('0.00');
});

// 当输入读数时计算用电量
$('#previousReading, #currentReading').on('input', function() {
    const currentReading = parseFloat($('#currentReading').val()) || 0;
    const previousReading = parseFloat($('#previousReading').val()) || 0;
    const consumption = Math.max(0, currentReading - previousReading);
    $('#consumption').text(consumption.toFixed(2));
});

// 打开抄表录入模态框
function openReadingModal() {
    // 重置表单
    $('#readingForm')[0].reset();
    $('#readingId').val('');
    $('#consumption').text('0.00');
    
    // 加载电表列表
    loadMeterList();
    
    // 设置当前日期
    const today = new Date().toISOString().split('T')[0];
    $('#readingDate').val(today);
    
    // 显示模态框
    $('#readingModal').modal('show');
}

// 编辑抄表记录
function editReading(id) {
    // 先加载电表列表
    loadMeterList();
    
    // 然后加载抄表记录数据
    $.ajax({
        url: `/api/meter-readings/${id}`,
        method: 'GET',
        success: function(data) {
            $('#readingId').val(data.readingId);
            $('#meterNoSelect').val(data.meterId);
            $('#previousReading').val(parseFloat(data.previousReading).toFixed(2));
            $('#currentReading').val(parseFloat(data.currentReading).toFixed(2));
            $('#readingDate').val(formatDate(data.readingDate));
            
            // 计算用电量
            const consumption = data.currentReading - data.previousReading;
            $('#consumption').text(consumption.toFixed(2));
            
            // 显示提示信息
            showAlert('修改本次读数将会自动更新后续抄表记录的上次读数', 'info');
            
            $('#readingModal').modal('show');
        },
        error: function(error) {
            console.error('加载抄表记录失败:', error);
            showAlert('加载抄表记录失败，请重试！', 'danger');
        }
    });
}

// 保存抄表记录
function saveReading() {
    // 表单验证
    const readingId = $('#readingId').val();
    const meterId = $('#meterNoSelect').val();
    const previousReading = parseFloat($('#previousReading').val());
    const currentReading = parseFloat($('#currentReading').val());
    const readingDate = $('#readingDate').val();

    if (!meterId) {
        showAlert('请选择电表！', 'danger');
        return;
    }
    if (isNaN(previousReading)) {
        showAlert('请输入上次读数！', 'danger');
        return;
    }
    if (isNaN(currentReading)) {
        showAlert('请输入本次读数！', 'danger');
        return;
    }
    if (!readingDate) {
        showAlert('请选择抄表日期！', 'danger');
        return;
    }

    // 验证读数逻辑
    if (currentReading < previousReading) {
        showAlert('本次读数不能小于上次读数！', 'danger');
        return;
    }

    const reading = {
        readingId: readingId || null,
        meterId: parseInt(meterId),
        previousReading: previousReading,
        currentReading: currentReading,
        electricityUsage: currentReading - previousReading,
        readingDate: readingDate
    };

    const url = readingId ? `/api/meter-readings/${readingId}` : '/api/meter-readings';
    const method = readingId ? 'PUT' : 'POST';

    // 如果是编辑操作，显示确认对话框
    if (readingId) {
        if (!confirm('确定要修改这条抄表记录吗？')) {
            return;
        }
    }

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(reading)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => Promise.reject(err));
        }
        return response.json();
    })
    .then(() => {
        $('#readingModal').modal('hide');
        readingsTable.ajax.reload();
        showAlert('抄表记录保存成功！', 'success');
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('保存失败：' + (error.message || '请重试！'), 'danger');
    });
}

// 删除抄表记录
function deleteReading(id) {
    if (confirm('确定要删除这条抄表记录吗？')) {
        fetch(`/api/meter-readings/${id}`, {
            method: 'DELETE'
        })
        .then(() => {
            readingsTable.ajax.reload();
            showAlert('抄表记录删除成功！', 'success');
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('删除失败，请重试！', 'danger');
        });
    }
}

// 退出登录
function logout() {
    if (confirm('确定要退出登录吗？')) {
        // 清除本地存储的用户信息
        localStorage.clear();
        // 跳转到登录页面
        window.location.href = '/login.html';
    }
}

// 显示提示信息
function showAlert(message, type) {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    `;
    
    // 移除现有的提示
    document.querySelectorAll('.alert').forEach(alert => alert.remove());
    
    // 查找插入位置
    let container = document.querySelector('.page-header');
    if (!container) {
        // 如果找不到 page-header，则插入到内容区域的开头
        container = document.querySelector('#content');
        if (container) {
            container.insertAdjacentHTML('afterbegin', alertHtml);
        }
    } else {
        container.insertAdjacentHTML('afterend', alertHtml);
    }
    
    // 自动关闭
    if (type === 'success' || type === 'info') {
        setTimeout(() => {
            const alert = document.querySelector('.alert');
            if (alert) {
                alert.remove();
            }
        }, 3000);
    }
}

function initializeCharts() {
    // 空实现，防止JS报错
} 

function loadRecentReadings() {
    // 空实现，防止JS报错
} 